package rpc_client_server;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

public class KeyValueServer {
	
	public static int NUMOFSERVERS = 5;
	public static void main(String[] args) {

		/** Create instances of the server object */
		Server[] myServers = new Server[NUMOFSERVERS];
		
		/**Instantiate five servers with given ports.*/
		for(int i = 0; i<NUMOFSERVERS ; i++){
			try {
				
				/**Create server with specified port and export it by using a stub.*/
				int port = i + 10000;
				String servername = "S"+ i;
				myServers[i] = new Server(servername,port);
				RemoteKeyValue theStub = (RemoteKeyValue) UnicastRemoteObject.exportObject(myServers[i], 0);
				Registry theServerRegistry = LocateRegistry.createRegistry(port);
				theServerRegistry.bind("RemoteKeyValue", theStub);
				
						
	
				System.out.println("Server S" +i +" is starting at port "+port );
	
				/** Publish it in the RMI registry.
				    Of course rmi registry should be running! */
				//Naming.rebind(RemoteKeyValue.LOOKUPNAME, im);
	
				//System.out.println("KeyValueServer ready.");
				
				} catch (Exception e) {
					System.err.println(e);
					System.exit(1);
				}
		}// end of for-loop
		
		/**Create others array for each server.*/
		for(int k = 0; k < myServers.length; k++){
			int index = 0;
			for(int l = 0; l < myServers.length; l++){
				if(myServers[k].myPort != myServers[l].myPort){
					myServers[k].others[index] = myServers[l].myPort;
					index++;
				}
			}
		}
	
	}
	
}
